<template>
  <div class="app-container">
    <el-button type="primary" class="go-back" @click="goBack">返回</el-button>

    <el-table
      v-loading="listLoading1"
      :data="tableBasic"
      element-loading-text="Loading"
      fit
      border
      highlight-current-row>
      <el-table-column prop="real_name" label="员工姓名"/>
      <el-table-column prop="personNumber" label="员工编号"/>
      <el-table-column prop="source" label="系统来源"/>
      <el-table-column prop="available" label="状态"/>
    </el-table>

    <h3>用户帐号（单条）
      <el-button v-if="event" type="primary" @click="addBind">新增绑定</el-button>
      <el-button v-if="event" type="danger" @click="endBind">结束绑定</el-button>
    </h3>
    <el-table
      v-loading="listLoadingUser"
      :data="table"
      element-loading-text="Loading"
      fit
      border
      highlight-current-row>
      <el-table-column prop="username" label="用户编号"/>
      <el-table-column prop="department" label="部门"/>
      <el-table-column prop="email" label="邮箱"/>
    </el-table>
    <el-dialog :visible.sync="addBindVisible" title="新增绑定" width="600px">
      <el-form ref="updateBind" :model="updateBindValue" :rules="updateBindValueRules" label-width="100px">
        <el-form-item
          label="绑定用户"
          prop="user_id">
          <el-select
            v-model="updateBindValue.user_id"
            :filter-method="filterUserId"
            :loading="getUserLoading"
            clearable
            placeholder="可输入部门查找"
            filterable>
            <el-option
              v-for="item in getUserIdValue"
              :key="item.id"
              :value="item.id"
              :label="item.realName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelUpdateBin">取 消</el-button>
          <el-button type="primary" @click="confirmUpdateBin('updateBind')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <h3>人员通用信息（单条）
      <el-button v-if="event" type="primary" @click="updatePerson('add')">新增</el-button>
      <el-button v-if="event" @click="updatePerson('edit')">编辑</el-button>
    </h3>
    <el-table
      v-loading="listLoadingPer"
      :data="personExtentionInfo"
      element-loading-text="Loading"
      fit
      border
      highlight-current-row>
      <el-table-column prop="phone" label="手机号"/>
      <el-table-column prop="phone_short" label="手机短号"/>
      <el-table-column prop="telephone" label="座机"/>
      <el-table-column prop="telephone_short" label="座机短号"/>
      <el-table-column prop="gender" label="性别"/>
      <el-table-column prop="business_service1" label="对外业务1"/>
      <el-table-column prop="business_service2" label="对外业务2"/>
      <el-table-column prop="emp_nature" label="用工性质"/>
      <el-table-column prop="emp_nature" label="证件照">
        <template slot-scope="scope">
          <img :src="scope.row.identification_photo">
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="updatePersonVisible" title="新增人员通用信息" width="600px">
      <el-form ref="updatePerson" :model="updatePersonValue" :rules="updatePersonValueRules" label-width="100px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="updatePersonValue.phone"/>
        </el-form-item>
        <el-form-item label="手机短号" prop="phone_short">
          <el-input v-model="updatePersonValue.phone_short"/>
        </el-form-item>
        <el-form-item label="座机" prop="telephone">
          <el-input v-model="updatePersonValue.telephone"/>
        </el-form-item>
        <el-form-item label="座机短号" prop="telephone_short">
          <el-input v-model="updatePersonValue.telephone_short"/>
        </el-form-item>
        <el-form-item label="对外业务1" prop="business_service1">
          <el-input v-model="updatePersonValue.business_service1"/>
        </el-form-item>
        <el-form-item label="对外业务2" prop="business_service2">
          <el-input v-model="updatePersonValue.business_service2"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="updatePersonValue.gender"/>
        </el-form-item>
        <el-form-item label="用工性质" prop="emp_nature">
          <el-input v-model="updatePersonValue.emp_nature"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelUpdatePerson">取 消</el-button>
          <el-button type="primary" @click="confirmUpdatePerson('updatePerson')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <h3/>
    <el-tabs class="filter-container" @tab-click="handleClick">
      <el-tab-pane v-for="item in tabs" :key="item.id" :label="item.text" :value="item">
        <el-button v-if="source&&item.id==='1'&& event" type="primary" @click="addOrganizationButton">绑定岗位</el-button>
        <el-table v-loading="listLoadingTab" :data="operatingPostList">
          <el-table-column v-for="list in currentTab.listFormTitle" :key="list.field" :prop="list.field" :label="list.label"/>
          <el-table-column v-if="source&&item.id==='1'&& event" label="操作">
            <template slot-scope="scope">
              <el-button @click="delOrganization(scope.row)">解绑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :visible.sync="addOrganizationVisible" title="新增工作岗位" width="600px">
      <el-row :gutter="20" style="margin-bottom: 20px" type="flex" justify="center">
        <el-col :span="12" :offset="2" class="tree">
          <div class="organization-post">组织机构</div>
          <el-tree
            v-loading="treeLoading"
            :data="frameworkData"
            :props="defaulfProp"
            :expand-on-click-node="false"
            accordion
            node-key="id"
            @node-click="handleNodeClick"/>
        </el-col>
        <el-col :span="12" :offset="1" class="post">
          <div class="organization-post">岗位</div>
          <el-radio-group v-loading="postLoading" v-model="addOrganizationValue.pid">
            <p v-for="item in postList" :key="item.objid" style="padding: 5px 0">
              <el-radio :label="item.code">{{ item.stext }}</el-radio>
            </p>
          </el-radio-group>
        </el-col>
      </el-row>
      <el-form ref="addOrganization" :model="addOrganizationValue" :rules="addOrganizationnValueRules" label-width="100px">
        <el-form-item label="岗位百分比">
          <el-input-number v-model="addOrganizationValue.vprozt" placeholder="请输入岗位百分比"/>
        </el-form-item>
        <el-form-item label="时间区域">
          <el-date-picker
            v-model="addOrganizationValue.vbegda"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="开始日期"/>
          <el-date-picker
            v-model="addOrganizationValue.vendda"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="结束日期"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelAddOrganization">取 消</el-button>
          <el-button type="primary" @click="confirmAddOrganization('addOrganization')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</template>

<script>
import commonApi from '@/api/commonApi'
export default {
  name: 'EmployeeInfo',
  data() {
    return {
      listLoading1: false,
      listLoadingUser: false,
      listLoadingPer: false,
      listLoadingTab: false,
      event: '', // 父组件是明细还是编辑传过来的事件
      source: '', // 父组件传过来的系统来源
      tabs: [],
      personNumber: '', // 父组件传过来的人员编号
      listData: [], // 获取的列表数据
      tableBasic: [{
        personNumber: '', // 父组件传过来的人员编号
        real_name: '', // 员工姓名
        source: '', // 系统来源
        available: '' // 状态
      }],
      table: [], // 用户帐号的列表数据
      personExtentionInfo: [], // 人员通用信息的列表数据
      operatingPostList: [], // 工作岗位信息数据
      addBindVisible: false, // 新增绑定的弹窗状态
      searchUserId: {
        currentNo: 1,
        pageSize: 100,
        data: {
          username: '',
          // real_name:"",
          department: ''
          // is_valid:'',
          // user_type:'',
        }
      },
      // 选中要绑定的人员
      updateBindValue: {
        user_id: '',
        otype: 'P',
        objid: ''
      },
      // 绑定事件表单的检验规则
      updateBindValueRules: {
        user_id: [
          { required: true, message: '请选择用户', trigger: 'blur' }
        ]
      },
      getUserLoading: false, // 加载人员列表状态
      bindTitle: '', // 绑定弹窗的title显示
      updatePersonVisible: false, // 人员通用信息的弹窗状态
      // 修改人员通用信息
      updatePersonValue: {
        personNumber: '',
        phone: '',
        phone_short: '',
        telephone: '',
        telephone_short: '',
        business_service1: '',
        business_service2: '',
        gender: '',
        emp_nature: ''
      },
      updatePersonTitle: '', // 更新人员通用信息的标题--（是新增还是编辑）
      currentTab: [], // 当前选中的tab，默认是第一个
      addOrganizationVisible: false, // 绑定岗位/人员的弹窗状态
      addOrganization: {
        objid: '',
        pup: null,
        vprozt: null,
        time: '',
        vbegda: '',
        vendda: ''
      },
      // 填写新增工作岗位信息
      addOrganizationValue: {
        objid: '', // 人员person_number
        pid: '', // 岗位code
        vprozt: '', // 百分比
        vbegda: '', // 开始时间
        vendda: ''// 结束时间
      },
      frameworkData: [], // 组织机构树
      defaulfProp: {
        children: 'nodes',
        label: function(data) {
          return data.objec.stext
        }
      },
      clickNodeData: {}, // 选中的节点数据
      postList: [], // 点击组织机构获得的岗位
      postLoading: false// 获取岗位的加载信息
    }
  },
  created() {
    this.tabs = this.$route.params.tabs
    // 一进来，让默认选中的是第一个tab数据
    this.currentTab = this.tabs[0]
    this.event = this.$route.params.event === 'edit'
    this.source = this.$route.params.source === 'HRSSP'
    this.personNumber = this.$route.params.personNumber
    this.updateBindValue.objid = this.$route.params.personNumber
    this.tableBasic[0].personNumber = this.$route.params.personNumber
    this.tableBasic[0].real_name = this.$route.params.real_name
    this.tableBasic[0].source = this.$route.params.source
    this.tableBasic[0].available = this.$route.params.available === true ? '可用' : '禁用'
    this.getTabData()
    this.getList()
    this.getPersonExtentionInfo()
  },
  methods: {
    // 返回
    goBack() {
      this.$router.go('-1')
    },
    // 获取用户帐号数据
    getList() {
      this.listLoadingUser = true
      commonApi('/organization/queryUserByPersonNumber/' + this.personNumber, 'get').then(response => {
        if (response.data !== null && response.code === 1) {
          this.table = [response.data]
        } else {
          this.table = null
        }
        this.listLoadingUser = false
      })
    },
    // 获取人员通用信息数据
    getPersonExtentionInfo() {
      this.listLoadingPer = true
      commonApi('/personExtentionInfo/queryPersonAdditionalInfoByPersonNumber/' + this.personNumber, 'get').then(response => {
        if (response.data !== null && response.code === 1) {
          this.personExtentionInfo = [response.data]
        } else {
          this.personExtentionInfo = null
        }
        this.listLoadingPer = false
      })
    },
    // 获取每个tab里面的接口值
    getTabData() {
      this.listLoadingTab = true
      commonApi(this.currentTab.apiUrl + this.personNumber, 'get').then(response => {
        if (response.data !== null && response.code === 1) {
          if (response.data.constructor === Array) {
            this.operatingPostList = response.data
          } else {
            this.operatingPostList = [response.data]
          }
        } else {
          this.operatingPostList = null
        }
        this.listLoadingTab = false
      })
    },
    // 获取用户列表数据
    getUserIdList() {
      this.getUserLoading = true
      commonApi('/user/queryUserByCondition', 'post', this.searchUserId).then(response => {
        if (response.code === 1) {
          this.getUserIdValue = response.data.rows
          this.getUserLoading = false
        }
      })
    },
    // 统一更改状态的方法
    updateVisible(visible) {
      this[visible] = !this[visible]
    },
    // 新增绑定事件
    addBind() {
      this.getUserIdList()
      this.updateVisible('addBindVisible')
    },
    // 绑定用户绑定的输入框
    filterUserId(e) {
      this.searchUserId.data.department = e
      this.getUserIdList()
    },
    // 确定修改绑定
    confirmUpdateBin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          commonApi('/organization/update', 'post', this.updateBindValue).then(response => {
            if (response.code === 1) {
              this.$message({
                type: 'success',
                message: '绑定成功'
              })
              this.getList()
              this.updateVisible('addBindVisible')
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          return false
        }
      })
    },
    // 确定结束绑定
    endBind() {
      if (this.table === null) {
        this.$message({
          type: 'warning',
          message: '请先绑定用户'
        })
      } else {
        this.$confirm('此操作将结束用户的绑定，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.updateBindValue.user_id = ''
          commonApi('/organization/update', 'post', this.updateBindValue).then(response => {
            if (response.code === 1) {
              this.$message({
                type: 'success',
                message: '解绑成功'
              })
              this.getList()
            }
          }).catch(err => {
            console.log(err)
          })
        }).catch()
      }
    },
    // 取消修改绑定
    cancelUpdateBin() {
      this.updateVisible('addBindVisible')
    },
    // 点击添加人员通用信息按钮
    updatePerson(title) {
      if (title === 'add') {
        // 因为接口只能添加一条信息
        if (this.personExtentionInfo !== null) {
          this.$message({
            type: 'warning',
            message: '只能添加一条信息'
          })
        } else {
          this.updatePersonTitle = '新增人员通用信息'
          this.updatePersonValue = {}
          this.updateVisible('updatePersonVisible')
        }
      } else {
        this.updatePersonTitle = '编辑人员通用信息'
        if (this.personExtentionInfo !== null) {
          this.updatePersonValue = this.personExtentionInfo[0]
          this.updateVisible('updatePersonVisible')
        } else {
          this.$message({
            type: 'warning',
            message: '请先添加人员'
          })
        }
      }
    },
    // 取消修改人员通用信息按钮
    cancelUpdatePerson() {
      this.updateVisible('updatePersonVisible')
    },
    // 确定修改人员通用信息
    confirmUpdatePerson(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = ''
          if (this.updatePersonTitle.indexOf('新增') > -1) {
            // 是新增功能
            url = '/personExtentionInfo/addAdditionalInfo'
          } else {
            // 是编辑功能
            url = '/personExtentionInfo/updateAdditionalInfo'
          }
          this.updatePersonValue.personNumber = this.personNumber
          commonApi(url, 'post', this.updatePersonValue).then(response => {
            if (response.code === 1) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.updateVisible('updatePersonVisible')
              this.getPersonExtentionInfo()
            }
          })
        } else {
          return false
        }
      })
    },
    // 切换tab点击事件
    handleClick(tab, event) {
      this.currentTab = tab.$attrs.value
      this.getTabData()
    },
    // 新增绑定岗位/人员
    addOrganizationButton() {
      this.updateVisible('addOrganizationVisible')
      if (this.frameworkData.length === 0) {
        this.getFrameworkTree()
      }
      this.addOrganizationValue.objid = this.personNumber
    },
    // 组织机构树
    getFrameworkTree() {
      this.treeLoading = true
      commonApi('/organization/tree', 'get').then(response => {
        if (response.code === 1) {
          this.frameworkData = response.data[0].nodes
        }
        this.treeLoading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    // 点击节点触发事件
    handleNodeClick(data, node) {
      this.clickNodeData = data
      this.getFrameworkDirectPost(data.objid)
    },
    // 获取组织结构直接岗位
    getFrameworkDirectPost(objId) {
      this.postLoading = true
      commonApi(`/organization/queryDirectPositionByOrganization/${objId}`, 'get').then(response => {
        if (response.code === 1) {
          this.postList = response.data
        }
        this.postLoading = false
      }).catch((err) => {
        console.log(err)
      })
    },
    // 删除绑定岗位/人员
    delOrganization(row) {
      this.$confirm(`确定要解绑岗位 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        commonApi('/organization/unbind', 'post', { code: this.personNumber + 'P', pid: row.code }).then(response => {
          if (response.code === 1) {
            this.$message({
              type: 'success',
              message: '解绑成功'
            })
            this.getTabData()
          }
        })
      }).catch(() => {
      })
    },
    // 点击取消绑定岗位/人员
    cancelAddOrganization() {
      this.updateVisible('addOrganizationVisible')
    },
    // 点击确定绑定岗位/人员
    confirmAddOrganization() {
      commonApi('/organization/bind', 'post', this.addOrganizationValue).then(response => {
        if (response.code === 1) {
          this.$message({
            type: 'success',
            message: '岗位绑定成功'
          })
          for (const obj in this.addOrganizationValue) {
            this.addOrganizationValue[obj] = ''
          }
          this.postList = []
          this.updateVisible('addOrganizationVisible')
          this.getTabData()
        }
      })
    }
  }
}
</script>

<style scoped>
  .go-back{
    float: right;
    margin-bottom: 5px;
  }
  .tree{
    border-right: 5px solid #F2F6FC
  }
  .post li{
    cursor: pointer;
  }
  .post li:hover{
    color: #3898EC;
  }
  .organization-post{
    text-align: center;
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 10px;
  }
</style>
